/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rhdtp.demopf.services;

import com.rhdtp.demopf.model.dto.Pelicula;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;

/**
 *
 * @author rhdtp
 */
public class ImageService {

    private static final Logger logger = Logger.getLogger(ImageService.class);

    /**
     * Creates a new instance of ImageService
     */
    public ImageService() {
    }

    public void addImage(Pelicula p) {
        String imagesPath;
        ExternalContext context;
        FacesContext facesContext = FacesContext.getCurrentInstance();
        File imagenPortada;
        FileOutputStream fileOutput;
        String relativeWebPath;
        String absoluteDiskPath;

        context = facesContext.getExternalContext();
        imagesPath = "/resources/images/peliculas/";

        try {
            relativeWebPath = imagesPath + p.getId() + "." + p.getTipoPortada();
            absoluteDiskPath = context.getRealPath(relativeWebPath);
            imagenPortada = new File(absoluteDiskPath);
            fileOutput = new FileOutputStream(imagenPortada);
            fileOutput.write(p.getPortada());
            fileOutput.close();
        } catch (IOException ioex) {
            logger.error(ioex.getCause(), ioex);
        }

    }
}
